<template>
	<view class="outbox">
		<view style="background: #f8f8f8;">
			<!-- #ifdef MP-WEIXIN -->
			<view v-if="false" class="u-f-c bluetooth">
				<view v-if="!isStop" class="u-f-c search">
					<text class="text">正在扫描附近的设备...</text>
					<image class="searchGIF" :animation="animationData"
						src="https://statics.xmcsrv.net/weixin/searchBle.gif"></image>
				</view>
				<!-- <view v-if="showWifi" class="u-f-sbc">
					<text class="newTitle">请打开Wi-Fi!</text>
					<image class="icon" src="https://statics.xmcsrv.net/weixin/warning.png"></image>
				</view> -->
				<view class="new u-f-sbc" v-if="list.length>0&&isEnd">
					<view class="u-f-c">
						<text class="newTitle">发现新设备</text>
						<view class="u-f-r" @click="toFindDeviceList">
							<image v-for="(item,index) in list" :key="index" class="icon"
								:src="item.deviceInfo.devicePic"></image>
						</view>
					</view>
					<uni-icons type="plus-filled" color="#14B4B0" size="30" @click="toFindDeviceList"></uni-icons>
				</view>
			</view>
			<view v-if="isStop&&list.length == 0" class="u-f-sbc reTry">
				<view class="u-f-r u-f-ac">
					<uni-icons type="info" size="30" color="#AFAFAF"></uni-icons>
					<view class="u-f-c" style="margin-left: 20rpx;">
						<text class="manualAdd">请尝试手动添加</text>
						<text class="msg">扫描不到怎么办？</text>
					</view>
				</view>
				<view class="tryBtn" @click="retryBtnAction">重试</view>
			</view>
			 <!-- #endif -->
			<view class="u-f-r u-f-ac u-f-ajc" :style="{marginTop:isEnd?'':'30rpx'}">
				<view class="line"></view>
				<view class="manual">{{$t('General.add.manualAddDevice')}}</view>
				<view class="line"> </view>
			</view>
			<!-- <j-cell-group style="margin: 20rpx;padding-bottom: 10rpx;"> -->
			<view class=""  style="margin: 20rpx;padding-bottom: 10rpx;border-radius: 15rpx;overflow: hidden;">
				<view class="" @click="onBindtapQrcode(), tapType = 1">
					<j-cell class="j-cell-t"  :title="$t('connectNet.qr_code_setup')" >
						<view class="cell-icons" slot="icon">
							<image src="https://statics.xmcsrv.net/weixin/Telkomsel/code.png" class="icon"></image>
						</view>
					</j-cell>
				</view>
				<j-cell v-if="false" class="j-cell-t"  title="扫描设备二维码" @tap="onBindtapScan" id="submit">
					<view class="cell-icons" slot="icon">
						<image src="https://statics.xmcsrv.net/weixin/scan.png" class="icon"></image>
					</view>
				</j-cell>
			</view>
			<!-- </j-cell-group> -->
			<!-- <j-cell-group> -->
			<view  style="margin: 20rpx;padding-bottom: 10rpx;">
				<j-cell class="j-cell-t" :more="false" id="submit">
					<view slot="icon">
						<image src="https://statics.xmcsrv.net/weixin/Telkomsel/addDeviceIcon.png" class="icon"></image>
					</view>
					<view slot="title">
						<input type="text" :placeholder="$t('General.add.manualAddDevice')" name="uuid" v-model="uuid" @input="bindInput" />
					</view>
					<view slot="tips">
						<view class="addBtn" @click="submit">{{ $t('General.add.addDevices') }}</view>
					</view>
				</j-cell>
			</view>
			<!-- </j-cell-group> -->
		</view>
		 <form v-if="false" class="form" @submit="submit">
            <view class="form-item">
                <input type="text" placeholder="输入设备序列号" name="uuid" v-model="uuid" class="form-control" @input="bindInput"/>
            </view>
            <view class="form-item" id="submit" >
                <button type="operation"  form-type="submit" style="border:none !important">添加设备</button>
            </view>
        </form>
		<!-- #ifdef MP-WEIXIN -->
		<view style="position: relative;margin-top: 20rpx;">
			<scroll-view scroll-y="true" class="side" :style="{height:topHeight}">
				<view class="side-item" :class="{'item-active':item.selected}" v-for="(item,index) in sortList"
					:key="index" @click="chooseSort(item)">{{item.objectName}}</view>
			</scroll-view>
			<view class="side-cont">
				<scroll-view class="rt-scro" scroll-y="true" :style="{height:topHeight}" :key="index">
					<view class="u-f-ajc u-f-c item2" v-for="(item,index) in deviceList" :key="index"
						@click="deviceDetail(item)">
						<image class="img" :src="item.devicePic" mode=""></image>
						<text>{{item.deviceTypeName}}</text>
					</view>
				</scroll-view>
			</view>
		</view>
		<uni-popup ref="devicePopup" :is-mask-click="false">
			<view class="devicePopup-connect">
				<view class="popup-device">
					<view class="title-number">
						<text>发现待添加设备：{{list.length}}个</text>
						<uni-icons type="closeempty" @click="closeDevicePopup()" size="24"></uni-icons>
					</view>
					<view class="device-list" @click="selectDevice(list[0])" v-if="list.length == 1">
						<view class="deviceImg">
							<image class="qrimg" :src="list[0].deviceInfo.devicePic" mode="">
							</image>
						</view>
						<view class="device-info">
							<view class="">
								{{list[0].deviceInfo.deviceTypeName?list[0].deviceInfo.deviceTypeName:''}}
							</view>
							<view class="text1">
								点击添加
							</view>
						</view>
					</view>
					<view class="device-list device-lists" v-if="list.length > 1">
						<view @click="selectDevice(item,index)" class="deviceImg" v-for="(item,index) in list"
							:key="index">
							<image class="qrimg" style="" :src="item.deviceInfo.devicePic" mode="">
							</image>
						</view>
					</view>
				</view>
				<!-- <view class="popup-device" >
					<view class="title-number">
						<text>发现待添加设备：{{list.length}}个</text>
						<uni-icons type="closeempty" size="24"></uni-icons>
					</view>
					<view class="device-list device-lists">
						<view @click="selectDevice(item,index)" class="deviceImg" v-for="(item,index) in list"
							:key="index">
							<image class="qrimg" style="" :src="item.deviceInfo.devicePic" mode="">
							</image>
						</view>
					</view>
				</view> -->
			</view>
		</uni-popup>
		<j-modal :value="locationPopup" class="" :showCancel="false" title="提示" @ok="closeLocationPopup">
			<view slot="content" class="popupCont">
				<view class="tips">在使用过程中，需要访问大致定位权限，用于发现附近设备及WiFi列表等功能. <br/> 如果不同意调用以上权限，将导致该功能无法正常使用,但不影响基本功能的使用。</view>
			</view>
		</j-modal>
		<j-modal :value="bluetoothPopup" :showCancel="false" title="提示" @ok="closeBluetoothPopup(1)">
			<view slot="content" class="popupCont">
				<image class="blth-gif" src="https://statics.xmcsrv.net/weixin/gif/openBluetooth1.gif" mode=""></image>
				<view class="tips">请在快捷菜单中开启手机蓝牙，用以扫描附近蓝牙设备</view>
			</view>
		</j-modal>
		<j-modal :value="wxBluetoothPopup" :showCancel="false" title="提示" @ok="closeBluetoothPopup(2)">
			<view slot="content" class="popupCont">
				<view class="tips">请在手机设置中将微信蓝牙权限打开</view>
			</view>
		</j-modal>
		 <!-- #endif -->
	</view>
</template>

<script>
	// const CryptoJS = require('crypto-js')
	// const Base64 = require('base64-js')

	const {
		ab2hex,
		hexToString,
		decryptBase64,
		hexStringToArrayBuffer,
		initTypes
	} = require('@/utils/util.js');
	export default {
		data() {
			return {
				uuid: '',
				list: [],
				searchLoad: true,
				connected: false,
				isStop: false,
				adapterState: {
					discovering: false,
					available: false
				},
				time: 15,
				timerId: null,
				showWifi: false,
				animationData: '',
				isEnd: false,
				virDevice: {},
				pid: '', //虚拟设备序列号
				url: '',
				deviceName: '',
				picUrl: '',
				sortList: [],
				objectId: '',
				deviceList: [],
				topHeight: '',
				tapType: 0, // 1 二维码配网   2 蓝牙配网
				available: false, //蓝牙是否可用
				discovering: false, //蓝牙是否可搜索
				isShowModel: false,
				bluetoothPopup:false,
				locationPopup:false,
				bluetoothSetting:false,
				wxBluetoothPopup:false,
                backShow: true,
			};
		},
		onUnload() {
			console.log('onUnload');
			if (this.timerId) {
				clearInterval(this.timerId)
			}
			this.stopBluetoothDevicesDiscovery();
			this.closeBluetoothAdapter();
		},
		onHide() {
			// #ifdef MP-WEIXIN
			console.log('onHide', this.timerId)
			if (this.timerId) {
				clearInterval(this.timerId)
			}
			if (this.tapType == 1) {
				this.stopBluetoothDevicesDiscovery();
				this.closeBluetoothAdapter();
				this.isShowModel = true;
			}
			this.closeDevicePopup();
			// #endif
		},
		onLoad() {
			// #ifdef MP-WEIXIN
			this.animation = uni.createAnimation({
				duration: 2000,
				delay: 2000,
				timingFunction: "linear",
			})
			let time = 4
			let timerId = setInterval(() => {
				time = time - 1
				if (time < 1) {
					this.isEnd = true
					clearInterval(timerId)
				}
			}, 1000)
			this.getWifiStatus()
			// this.move()
			this.$nextTick(() => {
				this.getClineHeight();
			})
			this.getRoomListByPage()
			// this.openBluetoothAdapter()
			this.getSortList()
			this.calNodeTop()
			wx.getLocation({
				type: 'gcj02',
				success (res) {
				}
			 })
			// this.virDevice.pid = 'ECSKT8360000000I'//'HADBL0002000100B'
			// this.getDeviceType()
			this.onBluetoothAdapterStateChange()
			// #endif
		},
		onShow() {
            uni.setNavigationBarTitle({
                title: this.$t('General.add.addDevices')
            })
			// #ifdef MP-WEIXIN
			this.time = 15
			this.setTimerId()
			this.startWifi()
			if (this.tapType == 1) {
				this.openBluetoothAdapter()
			}
			this.list = []
			this.checkSystemSettingAuth()
			// this.getDeviceGuidePage('HAPFR0001000100R')//HAPFR0001000100R   HAPFR0029000100Y
			// #endif
		},
		methods: {
			//监听蓝牙是否搜索
			onBluetoothAdapterStateChange(){
				var pages = getCurrentPages() // 获取栈实例
				let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
				uni.onBluetoothAdapterStateChange((res) => {
					console.log(res)
					console.log("蓝牙" + (res.available ? "可用" : "不可用"))
					console.log("蓝牙" + (res.discovering ? "开启" : "关闭") + "搜索");
					console.log(this.isShowModel)
					console.log(currentRoute, '页面')
					this.discovering = res.discovering;
					this.available = res.available
				})
			},
			closeBluetoothPopup(type){
				if(type == 1){
					this.bluetoothPopup = false
				}else{
					this.wxBluetoothPopup = false
				}
			},
			closeLocationPopup(){
				this.locationPopup = false
			},
			//判断手机蓝牙是否打开
			checkSystemSettingAuth(){
				this.$postPointData({code:'601103'})
				let systemSetting = wx.getSystemSetting()
				console.log('系统设置===',systemSetting);
                this.$logs({info: '获取系统设置权限===', res: systemSetting})
				if(!systemSetting.locationEnabled){
					this.locationPopup = true
				}else{
					this.checkLocationAuth()
				}
				this.bluetoothSetting = systemSetting.bluetoothEnabled
				if(!systemSetting.bluetoothEnabled){
					let system = uni.getSystemInfoSync().osName
					if(system == 'android'){
						this.bluetoothPopup = true
					}
				}else{
					wx.getSetting({
						success (res) {
							let authSetting = res.authSetting
							if(authSetting['scope.bluetooth'] === false){
								let obj = {
									code:'401107',
								    eventName:'bluetooth_get_permission_failed',
								    action:'cancel',
								    reason:'未开启蓝牙授权'
								}
								this.$postPointData(obj)
								wx.showModal({
									title: '您未开启蓝牙授权',
									content: '请在小程序系统设置中打开蓝牙授权，以便我们为您提供更好的服务',
									success: (res) => {
										if (res.confirm) {
											wx.openSetting()
										}
									}
								})
							}
						}
					})
				}
				this.openBluetoothAdapter()
			},
			//地理位置授权
			checkLocationAuth() {
				this.$postPointData({code:'601102'})
				wx.getSetting({
					success: (res) => {
						console.log('权限===',res);
						let authSetting = res.authSetting
						if (authSetting['scope.userLocation'] === false) {
							wx.showModal({
								title: '您未开启地理位置授权',
								content: '请在小程序系统设置中打开位置授权，以便我们为您提供更好的服务',
								success: (res) => {
									if (res.confirm) {
										wx.openSetting()
									}
								}
							})
						} 
				    }
				})
			},
			//获取设备添加引导页列表
			getDeviceGuidePage(pid){
				let data = {
					pid:pid
				}
				getApp().globalData.api.getDeviceGuidePageList(data, (result) => {
					console.log('根据PID获取引导页====', result);
					result.forEach((item)=>{
						if(item.displayType == 1){
							this.getDeviceGuideByPageId(item.params)
						}
					})
				});
			},
			//查询特定引导页
			getDeviceGuideByPageId(data){
				getApp().globalData.api.getDeviceGuideByPageId(data, (result) => {
					console.log('根据PID获取引导页====', result);
				});
			},
			onBindtapQrcode() {
				console.log('？？？？？')
				uni.navigateTo({
					url: '/jvss/pagesDevice/device/qrcode/device-powered?connecttype=qrcode'
				});
			},
			//选中左侧的分类
			chooseSort(item) {
				this.sortList.forEach((item2) => {
					if (item.id == item2.id) {
						item2.selected = true
					} else item2.selected = false
				})
				this.objectId = item.id
				this.getSortDeviceList()
			},
			// 计算节点位置
			calNodeTop() {
				let height = uni.getSystemInfoSync().screenHeight
				const query = uni.createSelectorQuery().in(this);
				query.select('#submit').boundingClientRect(data => {
					// console.log("得到布局位置信息" + JSON.stringify(data));
					// console.log("节点离页面顶部的距离为" + data.top,height);
					this.topHeight = (height - data.bottom) + 'px'
				}).exec();
			},
			//点击设备
			deviceDetail(item) {
				console.log('分类设备信息===',item);
				// this.getDeviceGuidePage(item.pid)
                const data = {
                    pid: item.parentPid
                }
                getApp().globalData.api.getDeviceGuidePageList(data, (res) => {
                    console.log(res, '获取到的信息1');
                    // console.log(res[0].pageType, '获取到的信息')
                    console.log(item.deviceTypeName);
                    // if(res.length>0&&!res[0].pageType)
                    let pageType = res[0]? res[0].pageType: ''
                    // if (item.deviceTypeName == '配网引导测试') {
                    if(!pageType&&res.length>0) {
                        console.log(123)
                        uni.navigateTo({
                            url: '/jvss/pagesDevice/device/device-add/device-guide?deviceName=' + item.deviceTypeName +
                                '&type=2&pageMsg=' + JSON.stringify(res)
                        })
                    } else {
                        uni.navigateTo({
                            url: '/jvss/pagesDevice/device/qrcode/device-powered?deviceName=' + item.deviceTypeName +
                                '&type=2&pageMsg=' + JSON.stringify(res) + '&connecttype=wifi'
                        })
                    }
                })

			},
			//获取左侧设备分类
			getSortList() {
				let data = {
					limit: 1000,
					page: 1
				}
				getApp().globalData.api.getDeviceSortListByPage(data, (result) => {
					console.log('dsdkflsdjfl', JSON.stringify(result));
					this.sortList = result.data
					this.sortList.forEach((item) => {
						this.$set(item, 'selected', false)
					})
					this.sortList[0].selected = true
					this.objectId = this.sortList[0].id
					this.getSortDeviceList()
					console.log('分类', this.sortList);

				});
			},
			//每个分类对应的设备列表
			getSortDeviceList() {
				let data = {
					limit: 1000,
					page: 1,
					objectId: this.objectId
				}
				getApp().globalData.api.getDeviceSortForDeviceType(data, (result) => {
					this.deviceList = result.data
					console.log('分类', this.sortList);
				});
			},

			//获取可视区域尺寸
			getClineHeight() {
				uni.getSystemInfo({
					success: (res => {
						this.move(res.screenWidth)
					})
				});
			},
			move(e) {
				let width = (e - 60) / 2
				this.animation.translate(width, -102)
					.scale(0.16)
					.step()
				this.animationData = this.animation.export()
			},
			//重试
			retryBtnAction() {
				this.openBluetoothAdapter((res)=>{
					this.isStop = false
					this.time = 15
					this.setTimerId()
				},
				(err)=>{
					
				})
				// if (!this.available) {
				// 	uni.showModal({
				// 		title: '提示',
				// 		content: '未检测到蓝牙开启，请打开蓝牙重试！',
				// 		showCancel: false,
				// 		success: function(res) {
				// 			if (res.confirm) {
				// 				console.log('用户点击确定');
				// 			} else if (res.cancel) {}
				// 		}
				// 	});
				// } else {
				// 	if (this.discovering) {
				// 		this.startBluetoothDevicesDiscovery()
				// 	} else {
				// 		this.openBluetoothAdapter()
				// 	}
				// 	this.isStop = false
				// 	this.time = 15
				// 	this.setTimerId()
				// }
			},
			//获取连接WiFi状态
			getWifiStatus() {
				uni.getNetworkType({
					success: (res) => {
						console.log('获取wifi信息', res);
						if (res.networkType != 'wifi') {
							this.showWifi = true
							uni.showModal({
								content: '检测到WiFi未连接或本地网络权限未启用，这将导致本地搜索设备失败。请转到配置以确认连接到WiFi并启用本地网络权限！',
							})
						} else {
							this.showWifi = false
						}
					}
				})
			},

			// 监听连接上 Wi-Fi 的事件
			//初始化 Wi-Fi 模块
			startWifi() {
				wx.startWifi({
					success: (res) => {
						// this.onWifiConnect()
						this.getConnectedWifi()
					},
					fail: (err) => {
						console.log('wifierr:', err);
					}
				})
			},
			getConnectedWifi() {
				wx.getConnectedWifi({
					partialInfo: false,
					success: res => {
						console.log('获取dddddddddddwifi===', res)
						// this.wifiName = res.wifi.SSID
					}
				})
			},
			//监听连接上 Wi-Fi 的事件
			onWifiConnect() {
				wx.onWifiConnectedWithPartialInfo((res) => {
					console.log('获取dddddddddddwifi===22', res)
					// this.wifiName = res.wifi.SSID
				})
			},
			//跳转路由器设置
			toRouterSetting(item) {
				uni.navigateTo({
					url: '../bluetooth/equipment-list??device=' + JSON.stringify(item.deviceInfo)
				})
			},
			//跳转找到设备页
			toFindDeviceList() {
				this.tapType = 2
				let list = []
				this.list.forEach((item) => {
					list.push(item.deviceInfo)
				})
				uni.navigateTo({
					url: '../bluetooth/findEquipment?deviceList=' + JSON.stringify(this.list)
				})
			},
			/*--------------------------------------蓝牙配网--------------------------------*/
			// 初始化蓝牙
			openBluetoothAdapter(callback,callErrback) {
				uni.openBluetoothAdapter({
					success: e => {
						console.log('初始化蓝牙成功:' + e);
						console.log(JSON.stringify(e));
						this.isStop = false;
						this.getBluetoothAdapterState();
						this.startBluetoothDevicesDiscovery()
						if(typeof callback == 'function'){
							callback()
						}
					},
					fail: e => {
						this.$postPointData({code:'401108', eventName:'bluetooth_open_failed',action:'cancel',reason:'初始化蓝牙失败'})
						console.log('ccccc===',e)
						console.log('初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg));
                        this.$logs({info: '初始化蓝牙失败', res: e})
						if(e.errno == 103 || e.errCode == 10001){
							let system = uni.getSystemInfoSync().osName
							if(system == 'ios'){
								if(!this.bluetoothSetting){
									if(e.state == 3){  // 3 iOS手机上微信里蓝牙权限被关闭  4 手机蓝牙被关闭
										this.wxBluetoothPopup = true
									}else if(e.state == 4){
										this.bluetoothPopup = true
									}
								}
							}
							return
						}
						if (e.errCode !== 0) {
							this.isShowModel = true;
							initTypes(e.errCode || e.errno, e.errMsg);
						}
						if(typeof callErrback == 'function'){
							callErrback()
						}
					}
				});
			},
			// 开始搜索蓝牙设备
			startBluetoothDevicesDiscovery() {
				uni.startBluetoothDevicesDiscovery({
					// services: ['A201'],
					success: e => {
						this.$postPointData({code:'601104'})
						console.log('开始搜索蓝牙设备:' + JSON.stringify(e));
						this.isStop = false;
						this.onBluetoothDeviceFound();
					},
					fail: e => {
						uni.showToast({
							title: e.errCode
						})
						console.log('搜索蓝牙设备失败：' + JSON.stringify(e));
						console.log('搜索蓝牙设备失败，错误码：' + e.errCode);
						if (e.errCode != 0) {
							// initTypes(e.errCode);
						}
					}
				});
			},
			// 停止搜索蓝牙设备
			stopBluetoothDevicesDiscovery(types) {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log('添加设备页面，停止搜索蓝牙设备:' + e.errMsg);
						this.isStop = true;
                        this.closeBluetoothAdapter()
					},
					fail: e => {
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							// initTypes(e.errCode);
						}
					}
				});
			},
			// 发现外围设备
			onBluetoothDeviceFound() {
				uni.onBluetoothDeviceFound(devices => {
					// console.log('开始监听寻找到新设备的事件', devices);
					this.getBluetoothDevices();
				});
			},
			// 根据 uuid 获取处于已连接状态的设备。
			getConnectedDevice() {
				uni.getConnectedBluetoothDevices({
					success: (res) => {
						console.log('获取处于已连接状态的设备', JSON.stringify(res));
					}
				})
			},
			// 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
			getBluetoothDevices() {
				uni.getBluetoothDevices({
					success: res => {
						// console.log('蓝牙设备list', JSON.stringify(res));
						let tempList = []
						this.list = []
						res.devices.forEach((item, index) => {
							let advertisDataStr = ab2hex(item.advertisData)
							if (advertisDataStr.endsWith('8b8b8b8b')||(advertisDataStr.startsWith('8b8b')&&(advertisDataStr.endsWith('02') || advertisDataStr.endsWith('03')))){
								console.log('搜索蓝牙设备xm=====', item);
								this.$logs({info: '发现蓝牙设备-XM设备列表', bluetoothItem: item})
								// this.list.push(item);
								for (let key in item.serviceData) {
									this.$set(item, 'pid', hexToString(ab2hex(item.serviceData[key])))
									this.$set(item, 'advertisDataStr', advertisDataStr)
									//根据Pid获取设备信息
									getApp().globalData.api.getDeviceInfoByPID({
										pid: hexToString(ab2hex(item.serviceData[key]))
									}, (result) => {
										if(result.data.code == 2000){
											this.$set(item, 'deviceInfo', result.data.data)
										}else{
											let info = {
												devicePic:'https://statics.xmcsrv.net/weixin/lockIcon.png',
												deviceTypeName:'屏显智能云锁'
											}
											this.$set(item, 'deviceInfo', info)
										}
									},false,false);
								}
								tempList.push(item)
								this.$postPointData({code:'601105'})
								this.$logs({info: '发现蓝牙设备-设备列表device-add', res: tempList,advertisDataStr:advertisDataStr})
							}
						})
						let isPush =false
						if(tempList.length !== 0){
							tempList.forEach((item)=>{
								if(item.serviceData){
									isPush = true
								}
							})
							if(isPush){
								this.list =tempList
							}
						}
						if (this.list.length !== 0) {
							this.list.forEach((item)=>{
								let info = {
									devicePic:'https://statics.xmcsrv.net/weixin/lockIcon.png',
									deviceTypeName:'屏显智能云锁'
								}
								if(!item.pid){
									this.$set(item, 'deviceInfo', info)
								}
							})
							setTimeout(() => {
                                if(this.backShow) {
                                    this.$refs.devicePopup.open();
                                    this.backShow = false
                                }
                                this.stopBluetoothDevicesDiscovery()
                                this.isEnd = true

							}, 100)
						}
						// console.log('设备列表：', this.list);
					},
					fail: e => {
						this.$postPointData({code:'401105', eventName:'bluetooth_get_system_info_error',error_code:e.errCode})
						console.log('获取蓝牙设备错误，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							// initTypes(e.errCode);
						}
					}
				});
			},

			// 选中的设备
			selectDevice(e, index) {
				console.log(e, index);
				// this.device = e
				// this.createBLEConnection()
				let list = []
				// this.list.forEach((item) => {
				// 	list.push(item.deviceInfo)
				// })
				list.push(e.deviceInfo)
				uni.navigateTo({
					url: '../bluetooth/findEquipment?deviceList=' + JSON.stringify(this.list)
				})
			},
			closeDevicePopup() {
				this.$refs.devicePopup.close();
			},

			// 获取本机蓝牙适配器状态
			getBluetoothAdapterState() {
				console.log('--->');
				uni.getBluetoothAdapterState({
					success: res => {
						console.log('获取本机蓝牙适配器状态成功', res);
						this.adapterState = res;
					},
					fail: e => {
						console.log('获取本机蓝牙适配器状态失败，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							// initTypes(e.errCode);
						}
					}
				});
			},
			/**
			 * 	断开蓝牙模块
			 */
			closeBluetoothAdapter() {
				uni.closeBluetoothAdapter({
					success: res => {
						console.log('断开蓝牙模块成功');
					}
				});
			},

			//定时
			setTimerId() {
				this.timerId = setInterval(() => {
					this.time = this.time - 1
					if (this.time == 0) {
						clearInterval(this.timerId);
						this.isStop = true;
						this.stopBluetoothDevicesDiscovery()
						this.calNodeTop()
					}
				}, 1000)
				this.calNodeTop()
			},
			bindInput(ev) {
				this.uuid = this.uuid.replace(/\s*/g, '')
			},
			// 扫描设备二维码
			onBindtapScan() {
				let self = this;
				uni.scanCode({
					success(res) {
						console.log('扫描设备二维码：', res);
						const uuid = res.result; // const len = uuid.length
						// if (res.errMsg === 'scanCode:ok' && (len === 16 || len === 20)) {
						if (res.errMsg === 'scanCode:ok') {
							if (uuid.length > 20) {
								if (uuid.includes('preview')) { //虚拟设备扫码预览
									let str = uuid.split('=')[1]
									console.log('============', str);
									self.virDevice = JSON.parse(decryptBase64(str))
									console.log('解密后的数据', self.virDevice);
									self.getDeviceType()
									self.getVirtualDeviceNo()
									this.$postPointData({code:'601600', eventName:'scan_qrcode_sys_add_dev_success'})
								} else if (uuid.includes('deviceDebug')) { //真机设备调试
									let str = uuid.split('=')[1]
									self.virDevice = JSON.parse(decryptBase64(str))
									self.uuid = self.virDevice.deviceNo
									console.log('解密后的数据', self.virDevice);
									self.skipH5()
									this.$postPointData({code:'601600', eventName:'scan_qrcode_sys_add_dev_success'})
									// self.getVirtualDeviceNo()
								} else {
									uni.showToast({
										title: '无效二维码',
										icon: 'none'
									});
								}
							} else {
								self.uuid = uuid
							}
						} else {
							uni.showToast({
								title: '无效二维码',
								icon: 'none'
							});
						}
					},
					fail(err) {
						console.log('error:', err);
					}
				});
			},
			isJson($string) {
				try {
					if (typeof JSON.parse($string) == 'object')
						return true;
					return false;
				} catch (e) {
					console.log(e);
					return false;

				}
			},
			//通过PID获取虚拟设备的序列号
			getVirtualDeviceNo() {
				let data = {
					pid: this.virDevice.pid
				}
				getApp().globalData.api.getVirtualDeviceNoByPID(data, (result) => {
					this.uuid = result
					this.addVirtualDevice()
				})

			},
			// 添加虚拟设备
			addVirtualDevice() {
				uni.showLoading({
					title: '正在加载'
				})
				let data = {
					userGroupId: uni.getStorageSync('currentGroupId'),
					deviceNo: this.uuid,
					deviceName: this.virDevice.deviceName,
					pid: this.virDevice.pid,
					nickName: uni.getStorageSync('userInfo').nickName,
					timeZone: 'Asia/Shanghai',
					devUserName: 'admin'
				};
				getApp().globalData.api.addDevice(data, (result) => {
					console.log('resultadvice', result);
					uni.hideLoading()
					if (result.data.code == 2000) {
						this.addVirtualDeviceToRoom()
					} else {
						if (result.data.msg == '设备已存在于当前用户组' || result.data.code == '-91013') {
							this.skipH5()
						} else {
							this.$postPointData({code:'401406', eventName:'scan_qr_code_sys_add_dev_failed',reason:result.data.msg,error_code:result.data.code})
							uni.showToast({
								title: result.data.msg,
								icon: 'none'
							});
						}
					}
				}, false, false)
			},
			// 添加虚拟设备到房间
			addVirtualDeviceToRoom() {
				let data = {
					deviceNo: [this.uuid],
					roomId: uni.getStorageSync('defaultRoom').id
				};
				getApp().globalData.api.addDeviceToRoom(data, (result) => {
					this.skipH5()
					if (result.data.code != 2000) {
						this.$postPointData({code:'401407', eventName:'scan_qr_code_add_to_room_failed',reason:result.data.msg,error_code:result.data.code})
					}
				})
			},
			skipH5() {
				let device = {
					adminToken: this.virDevice.adminToken || '',
					deviceNo: this.uuid,
					deviceName: this.virDevice.deviceName,
					userGroupId: this.virDevice.userGroupId || uni.getStorageSync('currentGroupId'),
					roomId: this.virDevice.roomId || uni.getStorageSync('defaultRoom').id,
					uiUrl: this.virDevice.url,
					devIcon: this.virDevice.picUrl,
					addType: 2
				}
				uni.navigateTo({
					url: `/jvss/pages/h5/h5?device=${encodeURIComponent(JSON.stringify(device))}`
				})
			},
			submit() {
				if (this.uuid.replace(/\s/g, '') === '') {
					uni.showToast({
						title: this.$t('General.add.addTips'),
						icon: 'none'
					});
					return;
				}
                console.log(this.uuid.replace(/\s/g, '').length)
                let length = this.uuid.replace(/\s/g, '').length
                if (length<16|| length>20) {
                    uni.showToast({
                        title: this.$t('General.add.addTips9'),
                        icon: 'none'
                    });
                    return;
                }
				uni.navigateTo({
					url: '/jvss/pagesDevice/device/device-add-next/device-add-next?uuid=' + this.uuid
				});
			},
			//获取房间列表
			getRoomListByPage() {
				const data = {
					userGroupId: uni.getStorageSync('currentGroupId'),
					page: 1,
					limit: 999
				};
				getApp().globalData.api.getRoomListByPage(data, (result) => {
					uni.setStorageSync('defaultRoom', result.data[0])
				});
			},
			//获取设备信息
			getDeviceType() {
				let data = {
					pid: this.virDevice.pid
				}
				getApp().globalData.api.getDeviceType(data, (result) => {
					this.virDevice.picUrl = result.devicePic
				});
			},
		}
	};
</script>
<style lang="scss">
	page {
		background: #ffffff;
		// padding: 20rpx 0;
	}
	/deep/ .cell-group-item {
		padding: 0rpx;
	}

	::v-deep .cell-group-item {
		padding: 0rpx;
	}

	.outbox {
		// padding:0rpx 30rpx;
		// background: #F8F8F8;
		// margin: 20rpx;
	}

	.reTry {
		margin: 10rpx 20rpx 30rpx 20rpx;
		background: white;
		border-radius: 10rpx;
		padding: 30rpx 20rpx;

		.manualAdd {
			font-weight: bold;
		}

		.msg {
			color: #FF0025;
			font-size: 24rpx;
		}

		.tryBtn {
			border-radius: 8rpx;
			border: 1rpx solid red;
			padding: 8rpx 25rpx;
			color: red;
		}
	}

	.bluetooth {
		// padding: 15rpx 0;
		padding: 20rpx;

		.search {
			position: relative;
			color: #999999;
			font-size: 24rpx;

			image {}

			.text {
				width: 300rpx;
			}
		}

		.searchGIF {
			position: absolute;
			// transform: translateX(50%);
			left: 50%;
			margin: 50rpx 0;
			margin-left: -150rpx;
			width: 300rpx;
			height: 300rpx;
		}

		.icon {
			width: 50rpx;
			height: 50rpx;
			margin-right: 15rpx;
		}

		.new {
			margin-top: 20rpx;
			background: #F7F6FB;
			border-radius: 10rpx;
			padding: 30rpx 20rpx;

			.newTitle {
				font-weight: 600;
				font-size: 26rpx;
				margin-bottom: 20rpx;
			}
		}

	}

	.line {
		width: 190rpx;
		height: 2rpx;
		background: #999;
	}

	.manual {
		font-weight: 600;
		font-size: 26rpx;
		margin: 0 20rpx;
	}

	.form {
		width: auto;
	}

	.form-item {
		padding: 10rpx 0;
	}

	.form-control {
		// border-top: 1px solid #eeeeee;
		// border-bottom: 1px solid #eeeeee;
		width: 96%;
		margin: auto;
		padding: 20rpx 0;
		text-align: center;
		font-size: 28rpx;
	}

	.addBtn {
		width: 160rpx;
		height: 46rpx;
		background: rgba(255, 255, 255, 0.39);
		border: 1px solid #FF0025;
		border-radius: 23rpx;
		text-align: center;
		color: #FF0025;
		margin-right: 20rpx;
		font-size: 26rpx;
		align-items: center;
		display: flex;
		justify-content: center;

	}

	.scan {
		margin-top: 120rpx;
		text-align: center;
		font-size: 24rpx;
		color: #999999;
	}

	.j-cell-t {
		.cell-image {
			width: 40rpx !important;
			height: 40rpx !important;
		}
	}

	.icon {
		width: 50rpx;
		height: 50rpx;
		margin-left: 20rpx;
	}

	.side {
		position: absolute;
		left: 0; //-50rpx;
		width: 170rpx;
		height: calc(100vh - 500rpx);
		background: white;

		.side-item {
			font-size: 26rpx;
			color: #494949;
			padding: 20rpx;
			text-align: center;
		}

		.item-active {
			color: #FF0025;
		}
	}

	.rt-scro {
		/deep/.uni-scroll-view-content {
			height: 0;
			display: flex;
			flex-wrap: wrap;
		}
	}

	.side-cont {
		position: absolute;
		left: 170rpx; //120rpx;
		height: calc(100vh - 500rpx);
		width: calc(100vw - 170rpx);
		flex-wrap: wrap;
		// display: flex;
		flex-direction: row;
		align-items: flex-start;
		background: white;

		.item2 {
			width: calc((100vw - 170rpx)/2);
			align-items: center;
			display: inline-table;
			justify-content: center;
			text-align: center;

			.img {
				width: 110rpx;
				height: 110rpx;
				margin: 20rpx;
			}

			text {
				margin: 10rpx 0;
				font-size: 24rpx;
				padding: 0 20rpx;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 3;
				text-overflow: ellipsis;
				word-break: break-all;

			}
		}
	}

	.popup-device {
		width: 90vw;
		// height: 294rpx;
		padding-bottom: 30rpx;
		background: #FFFFFF;
		border-radius: 15rpx;
		opacity: 1;
		margin-top: 20rpx;
		position: absolute;
		margin-left: -45vw;
		/* bottom: 10px; */
		margin-top: 20vh;

		.title-number {
			display: flex;
			justify-content: space-between;
			padding: 20rpx;
			padding: 20rpx 20rpx 20rpx 40rpx;
			font-weight: bold;
		}

		.device-list {

			display: flex;
			align-items: center;

			.deviceImg {
				width: 150rpx;
				height: 150rpx;
				margin-left: 20rpx;
				flex-shrink: 0;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.device-info {
				font-size: 28rpx;
				color: #2B2B2B;
				margin-left: 20rpx;
			}

			.text1 {
				font-size: 22rpx;
				color: #B8B8B8;
				margin: 10rpx 0;
			}
		}

		.device-lists {
			width: 100%;
			overflow-x: auto;
		}
	}
	/deep/.j-modal-content{
		width: 80vw;
		max-height: 80vh;
	}
	.popupCont{
		.blth-gif{
			width: 300rpx;
			height: 563rpx;
		}
		.tips{
			color: #aca8ac;
			font-size: 26rpx;
			margin-top: 20rpx;
		}
	}
</style>
